package cn.hxzy.icon.icon.controller;

import cn.hxzy.icon.icon.entity.User;
import cn.hxzy.icon.icon.entity.vo.ReturnBean;
import cn.hxzy.icon.icon.service.UserService;
import cn.hxzy.icon.icon.uitl.VerifyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class PublicController {

    @Autowired
    private UserService userService;

    /**
     * 登录验证
     *
     * @param verify
     * @param loginName
     * @param loginPassword
     * @param session
     * @return
     */
    @PostMapping("login")
    public ReturnBean login(String verify, String loginName, String loginPassword, HttpSession session) {
//        if (verify != null && verify != "") {
////            判断验证码是否存在
//            Object attribute = session.getAttribute(VerifyUtil.RANDOMCODEKEY);
//            if (verify.equals(attribute)) {
                //判断验证码是否匹配
                User user = userService.findByLoginNameAndLoginPassword(loginName, loginPassword);
                if (user != null) {
                    //判断对象时否为空
                    session.setAttribute("loginUser", user);
                    return ReturnBean.of(ReturnBean.AnswerCode.SUCCESS, user);
                }
                return ReturnBean.of(ReturnBean.AnswerCode.AUTH_ERROR);
            }
//            return ReturnBean.of(ReturnBean.AnswerCode.VERIFY_ERROR);
//        }
//        return ReturnBean.of(ReturnBean.AnswerCode.VERIFY_NOT_EXIST);
//    }

    /**
     * 验证是否登录用户
     *
     * @param session
     * @return
     */
    @PostMapping("userInfo")
    public ReturnBean userInfo(HttpSession session) {
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser != null) {
            return ReturnBean.of(ReturnBean.AnswerCode.SUCCESS, loginUser);
        }
        return ReturnBean.of(ReturnBean.AnswerCode.NOT_LOGIN);
    }

    /**
     * 验证码
     *
     * @param request
     * @param response
     */
    @GetMapping("verify")
    public void verify(HttpServletRequest request, HttpServletResponse response) {
        VerifyUtil.getRandcode(request, response);
    }

    /**
     * 退出
     *
     * @param session
     * @return
     */
    @PostMapping("logout")
    public void logout(HttpSession session) {
        session.invalidate();
    }
}
